<template>
  <div class="history-box" v-infinite-scroll="handleLoad" :infinite-scroll-disabled="disable" :infinite-scroll-distance="100">
    <div class="header">
      <div class="title"> 历史记录</div>
      <div class="operation">
        <el-switch v-model="recordStatus" />
        记录浏览历史
      </div>
    </div>
    <div style="display: flex">
      <div class="prompt" v-if="deleteAction">
        已经选择{{checkList.length}}条视频
        <el-button type="warning" @click="handleDelete"><el-icon><Delete /></el-icon>删除</el-button>
      </div>
      <div class="prompt" v-else></div>
      <div class="about-operation">

        <el-button @click="refresh"><el-icon><Refresh /></el-icon>刷新</el-button>
        <el-input placeholder="搜索up主/标题" v-model="param.keyword" style="width: 240px"></el-input>
        <el-button type="primary" @click="HandleSearchHistory">搜索</el-button>
        <el-button @click="dialogVisible = true"><el-icon><BrushFilled /></el-icon>清空历史</el-button>
        <el-button v-if="!deleteAction" @click="deleteAction = true"><el-icon><Operation /></el-icon>批量管理</el-button>
        <el-button v-else @click="deleteAction = false"><el-icon><Operation /></el-icon>退出管理</el-button>
      </div>
    </div>

    <el-timeline style="max-width: 1280px">

      <ul  class="infinite-list">
        <template v-if="!deleteAction">
          <el-timeline-item v-for="item in resultList" :timestamp="item.date" placement="top">

        <div class="grid-container">
          <div class="grid-item" v-for="subItem in item.items" :key="subItem.id">
            <div class="save-pic" @click="toVideoDetail(subItem.videoId)">
              <img class="pic" :src="subItem.videoCover" alt="">
            </div>
            <div class="title">{{subItem.videoTitle}}</div>
            <div class="author-time">
              <span class="author" style="cursor: pointer" @click="toOtherSpace(subItem.videoOwnerId)">{{subItem.videoOwnerNickname}}</span>
              ·
              {{subItem.watchTime}}
            </div>
          </div>

        </div>
      </el-timeline-item>
        </template>
        <el-checkbox-group v-else v-model="checkList" size="large">
          <el-timeline-item v-for="item in resultList" :timestamp="item.date" placement="top">
            <div class="grid-container">
              <div class="grid-item" v-for="subItem in item.items" :key="subItem.id">
                <el-checkbox style="position: absolute;right: 5px;top:5px" :value="subItem.historyId" />
                <div class="save-pic" @click="toVideoDetail(subItem.videoId)">
                  <img class="pic" :src="subItem.videoCover" alt="">
                </div>
                <div class="title">{{subItem.videoTitle}}</div>
                <div class="author-time">
                  <span class="author" style="cursor: pointer" @click="toOtherSpace(item.userId)">{{subItem.nickname}}</span>
                  ·
                  {{subItem.watchTime}}
                </div>
              </div>
            </div>
          </el-timeline-item>
        </el-checkbox-group>
      </ul>
    </el-timeline>
    <el-dialog
        v-model="dialogVisible"
        title="清空历史"
        width="500"
    >
      <span>你确定要清空历史吗？请谨慎考虑</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="warning" @click="clearHistory">
            我确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import {onMounted, reactive, ref} from "vue";
import {constants} from "@/constant/constant.js"
import {clearMyHistory, deleteHistory, getHistoryList} from "@/api/api.js";
import {useUserStore} from "@/stores/userInfoStore.js";
import {useRouter} from "vue-router";
import {ElMessage} from "element-plus";
/*用户状态*/

let currentUserId = 0
/*页面刷新时*/
const watchHistoryList = ref([])
onMounted(async ()=>{
  currentUserId = useUserStore().userInfo.userId
  if(!currentUserId){
    currentUserId = Number(localStorage.getItem("userId"));
  }
  await load()
})


/*下拉获取更多*/
/**
 * 加载更多数据
 * @returns {Promise<void>}
 */
const disable = ref(false)
const param = reactive({
  page:0,
  pageSize:2,
  keyword:''
})
const load = async (replace = false) => {
  // console.log("开始加载更多数据")
  param.page+=1;
  // console.log(param.page)
  const res = await getHistoryList(currentUserId,param)
  // console.log(res)
  const status = res.data.length === 0
  // console.log(status ? "没有更多数据了" : "加载成功")
  if(status) {
    disable.value = true
  }
  if(replace){ //是否替换数据
    watchHistoryList.value = []
  }
  res.data.forEach(item=>{ // 将数据添加到数组中
    watchHistoryList.value.push(item)
  })
  resultList.value = groupByDate(watchHistoryList.value);
  console.log(resultList.value)
}
const handleLoad = async ()=>{
  await load()
}

/*状态相关 */
const recordStatus = ref()

/*跳转到详情*/
const router = useRouter()
const toVideoDetail = (videoId)=>{
  console.log(videoId)
  router.push({
    name:'video',
    params:{
      videoId
    }
  })
}
const toOtherSpace = (userId) => {
  router.push({
    name:'home',
    params:{
      userId
    }
  })
}







const resultList = ref()
/*工具函数*/
/**
 * 分组函数
 * @param historyList
 * @returns {{date: *, items: *}[]}
 */
function groupByDate(historyList) {
  // 创建一个空对象，用于存储分组后的数据
  const grouped = {};
  // 遍历历史记录列表
  historyList.forEach(item => {
    // 提取日期部分（假设 watchTime 的格式是 "YYYY-M-D HH:mm"）
    const date = item.watchTime.split(' ')[0];

    // 如果该日期还没有在分组对象中，则创建一个空数组
    if (!grouped[date]) {
      grouped[date] = [];
    }

    // 将当前对象添加到对应日期的数组中
    grouped[date].push(item);
  });
  console.log(grouped)
  // 将分组后的对象转换为数组形式
  const result = Object.keys(grouped).map(date => ({
    date: date,
    items: grouped[date]
  }));

  return result;
}

/*搜索相关*/
const HandleSearchHistory = ()=>{
  param.page = 0;
  load(true) // 搜索要重新加载数据，替换原有数据
}
/* 刷新 */
const refresh = ()=>{
  param.page = 0;
  param.pageSize = 20;
  load(true) // 搜 索要重新加载数据，替换原有数据
}

/* 删除历史记录相关 */
const deleteAction = ref(false)
const checkList = ref([])
const dialogVisible = ref(false)
const handleDelete = async ()=>{
  console.log(checkList.value)
  await deleteHistory(checkList.value)
}

const clearHistory = ()=>{
  try{
    clearMyHistory()
    dialogVisible.value = false;
    refresh()
    ElMessage.success('清空成功')
  }catch (e) {
    ElMessage.error('清空失败'+e.message)
  }
}
</script>
<style scoped lang="scss">
.infinite-list {
  //height: 500px;
  overflow-y: auto;
  //background-color: #ff37dd;
  padding: 0;
  margin: 0;
  list-style: none;
}
.history-box{
  height: 650px;
  background-color: #ffffff;
  overflow-y: auto;
  //width: 1180px;
  //margin: 10px auto;
  padding: 1% 5%;
}
.header{
  height: 80px;
  padding-left: 30px;
  display: flex;
  justify-content: space-between;
  .title{
    color: black;
    font-size: 27px;
    font-weight: bold;
  }
  .operation{

  }
}
.prompt{
  box-sizing: border-box;
  width: 650px;
  padding-left: 30px;
}
.about-operation{
  height: 50px;
  //padding-left: 650px;
}
.grid-container {
  width: 1150px;
  display: grid;
  grid-template-columns: repeat(4, 1fr); /* 5列，每列等宽 */
  gap: 16px; /* 列与列、行与行之间的间距 */
  .grid-item {
    position: relative;
    //background-color: #f0f0f0; /* 背景色 */
    //padding: 16px; /* 内边距 */
    //text-align: center; /* 文本居中 */

    //border-radius: 8px; /* 圆角 */
    height: 250px;
    display: flex;flex-direction: column;
    justify-content: space-around;
    .save-pic{
      border-radius: 8px; /* 圆角 */
      height: 160px;
      overflow: hidden;
      .pic{
        width: 100%;
      }
    }
    .title{
      min-height: 25px;
      font-size: 14px;
    }
    .author-time{
      font-size: 12px;
      color: gray;
    }
  }
}

:deep(.el-checkbox.el-checkbox--large .el-checkbox__inner) {
  height: 25px;
  width: 25px;
  font-size: 20px;
}

:deep(.el-checkbox__inner:after) {
  border: 1px solid transparent;
  border-left: 0;
  border-top: 0;
  box-sizing: content-box;
  content: "";
  height: 12px;
  left: 10px;
  position: absolute;
  top: 5px;
  transform: rotate(45deg) scaleY(0);
  transform-origin: center;
  transition: transform .15s ease-in .05s;
  width: 3px;
}
</style>